<?php

declare(strict_types=1);
/**
 * 
 */
namespace WanZ\App\User\Logic;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use WanZ\App\User\Logic\Traits\UserTrait;
use WanZ\App\User\Logic\Traits\SmsTrait;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;

/**
 * Sms管理.
 *
 * Class SmsLogic
 */
class SmsLogic
{
    use SmsTrait;
    use UserTrait;

    /**
     * 发送验证码
     *
     * @param string $code
     * @param string $type
     * @param string $phone
     * @param int $companyId
     * @return bool
     * @throws CommonException
     */
	protected function sendSMS(string $code = '', string $type = '', string $phone = '', int $companyId = 0): bool
    {
	    return $this->sendVerificationCodeByType($phone, $companyId, $type);
	}

    /**
     * 发送验证码
     *
     * @param string $phone
     * @param string $type
     * @param int $company_id
     * @return bool
     * @throws CommonException
     */
	public function sendCode(string $phone = '', string $type = '', int $companyId = 0): bool
	{
		if (empty($phone) || $companyId <= 0 || empty($type)) {
		    throw new CommonException(ErrorCode::INVALID_PARAMS, '发送验证码失败，参数非法');
        }

		if (substr($type, 0, 8) == 'register') {
			$type2 = substr($type, 9);
			if (empty($type2)) {
				// 说明是运营商注册，这里不需要操作
			} else {
				if (!in_array($type2, config('login.type'))) {
					throw new CommonException(ErrorCode::INVALID_PARAMS, '手机号验证类型缺失（支付宝 OR 微信）');
				}
				if ($this->checkPhoneExists($phone, $type2)) {
					throw new CommonException(ErrorCode::INVALID_PARAMS, '该手机号已被注册');
				}
				$type = 'register';
			}
		}

        return $this->sendVerificationCodeByType($phone, $companyId, $type);
	}

    /**
     * 验证验证码
     *
     * @param string $phone
     * @param string $type
     * @param string $code
     * @return bool
     * @throws CommonException
     */
	public function checkSMSCode(string $phone = '', string $type = '', string $code = ''): bool
	{
	    if (empty($phone) || empty($code) || empty($type)) {
	        throw new CommonException(ErrorCode::INVALID_PARAMS, '校验验证码失败，参数非法');
        }

	    return $this->verifyCodeHandle($phone, $type, $code);
	} 
}
